import { createRouter, createWebHistory } from 'vue-router';
import LoginPage from '../views/Login.vue';
import HomePage from '../views/Home.vue';
import ServerPage from '../views/Server.vue';
import OrderPage from '../views/Order.vue';
import RegisterPage from '../views/Register.vue';
import PersonPage from '../views/Person.vue';
import PetPage from '../views/Pet.vue';
import { ElMessage } from 'element-plus';

const routes = [
  { path: '/', component: LoginPage },
  { path: '/register', component: RegisterPage },
  { path: '/home', component: HomePage, meta: { requiresAuth: true } },
  { path: '/server', component: ServerPage, meta: { requiresAuth: true } },
  { path: '/order', component: OrderPage, meta: { requiresAuth: true } },
  { path: '/person', component: PersonPage, meta: { requiresAuth: true } },
  { path: '/pet', component: PetPage, meta: { requiresAuth: true } }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token') || sessionStorage.getItem('token');

  if (to.meta.requiresAuth && !token) {
    ElMessage.warning('还未登录，请先登录');
    next('/');
  } else {
    next();
  }
});

export default router;
